package com.unlcn.erp.hyc.interfaces.backend.service;

import com.alibaba.fastjson.JSONObject;
import com.unlcn.erp.hyc.interfaces.backend.bo.ReceivableBillDetail;
import com.unlcn.erp.hyc.interfaces.backend.bo.ReceivableBillMain;
import com.unlcn.erp.hyc.interfaces.backend.bo.ReceivableCodesDB;
import com.unlcn.erp.hyc.interfaces.backend.enums.CallHYCUrlTypeEnum;
import com.unlcn.erp.hyc.interfaces.base.mapper.*;
import com.unlcn.erp.hyc.interfaces.base.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by zoupx on 2017-09-06.
 */
@Service
public class CallReceivableCodesServiceImpl  implements CallReceivableCodesService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CallWayBillByHYCServiceImpl.class);

    @Autowired
    private SmreceivablecodesmainMapper smreceivablecodesmainMapper;
    @Autowired
    private SmreceivablecodesdetailMapper smreceivablecodesdetailMapper;
    @Autowired
    private ArorderMapper arorderMapper;
    @Autowired
    private SoorderMapper soorderMapper;
    @Autowired
    private HycorderMapper hycorderMapper;
    @Autowired
    private SoshiplineMapper soshiplineMapper;
    @Autowired
    private CallHYCUrlReceiveService callHYCUrlReceiveService;
    @Autowired
    private HycExceptionMsgMapper hycExceptionMsgMapper;
    @Autowired
    private ExecptionDisposeService execptionDisposeService;

    private static final String  RECCODES = "RECCODES" ,RECDETAIL = "RECDETAIL";

    //根据应收账单列表中间表数据更新到erp的应收表
    @Override
    public void updateArorder() throws Exception {
        SmreceivablecodesmainExample  smreceivablecodesmain=new SmreceivablecodesmainExample();
        //查询默认未处理的数据
        smreceivablecodesmain.createCriteria().andVcflagEqualTo("0");
        List<Smreceivablecodesmain>  list= smreceivablecodesmainMapper.selectByExample(smreceivablecodesmain);
        // select *  from  smPayCodesMain
        LOGGER.debug("查询出应收主表数据量"+list.size());
        DealRecMain(list);
    }
    //处理主数据
    public void DealRecMain(List<Smreceivablecodesmain> list) throws Exception{
        for(int i = 0; i < list.size() ; i++ ){
            Smreceivablecodesmain smreceivablecodesmain = list.get(i);
            Boolean isflag = DealRecDetail(smreceivablecodesmain);
            // 更新主表狀態為1
            if(isflag){
                smreceivablecodesmainMapper.updateByIlineid(smreceivablecodesmain.getIlineid());
                LOGGER.info(smreceivablecodesmain.getBillcode()+"应收账单保存成功");
            }
        }
    }
    //处理明细数据
    public Boolean DealRecDetail(Smreceivablecodesmain smreceivablecodesmain) throws Exception{
        LOGGER.debug("查询出应收明细表数据量"+smreceivablecodesmain.getBillcode());
        SmreceivablecodesdetailExample  smreceivablecodesdetail =new SmreceivablecodesdetailExample();
        //查询默认未处理的数据
        smreceivablecodesdetail.createCriteria().andVcflagEqualTo("0").andBillcodeEqualTo(smreceivablecodesmain.getBillcode());

        List<Smreceivablecodesdetail>  list= smreceivablecodesdetailMapper.selectByExample(smreceivablecodesdetail);
        int iflag = 0 ;
        for(int i = 0; i < list.size() ; i++ ){
            Smreceivablecodesdetail  detail = list.get(i);
            // Arorder arorder =new Arorder();

            Arorder saveArorder =new Arorder();
            //生产环境下面打开
            List<ArorderSo> arorderlist=arorderMapper.selectByVcorderno(detail.getOrdercode());
            //List<ArorderSo> arorderlist=arorderMapper.selectByVcorderno("L16001610");

            if(!CollectionUtils.isNotEmpty(arorderlist)) continue;

            ArorderSo  ar= arorderlist.get(0);

            LOGGER.debug("得到Soilineid"+ar.getSoilineid());
            LOGGER.debug("得到Vcorderno"+ar.getVccustshipno());
            saveArorder.setVccustshipno(ar.getVccustshipno());
            // Short  sh=Short.parseShort(ar.getSoilineid());
            // Short sh=new Short(ar.getSoilineid());
            //需要
            saveArorder.setIorderid(Integer.valueOf(ar.getSoilineid()));
            LOGGER.debug("saveArorder.setIorderid"+saveArorder.getIorderid());
            //saveArorder.setIpayid(Short.valueOf("1"));
            if("10".equals(smreceivablecodesmain.getInvoicestatus())){
                saveArorder.setIpayid(1);
            }else{
                saveArorder.setIpayid(2);
            }
            saveArorder.setDtorderdate(ar.getDtorderdate());
            saveArorder.setDcqty(Integer.valueOf("1"));
            saveArorder.setDtshipprint(ar.getDtshipprint());
            saveArorder.setIstartcityid(ar.getIstartcityid());
            saveArorder.setVcstartcityname(ar.getVcstartcityname());
            saveArorder.setIdestcityid(ar.getIdestcityid());
            saveArorder.setVcdestcityname(ar.getVcdestcityname());

            saveArorder.setIcustomerid(ar.getIcustomerid());
            saveArorder.setIcontractid(ar.getIcontractid());
            saveArorder.setIwarehouseid(ar.getIwarehouseid());

            saveArorder.setDcarkilometer(1);
            saveArorder.setDcprice(Double.parseDouble(detail.getSettlecost()));

            //取慧运车接口数据结算金额对应erp的汇总金额
            saveArorder.setDctotal(Double.parseDouble(detail.getSettlecost()));

            saveArorder.setDtshipdate(ar.getDtshipdate());
            saveArorder.setDtcomedate(ar.getDtcomedate());
            saveArorder.setIshipid(ar.getIshipid());
            saveArorder.setIshiplineid(ar.getIshiplineid());
            saveArorder.setIstyleid(ar.getIstyleid());
            saveArorder.setVcstyleno(ar.getVcstyleno());
            saveArorder.setIcheck(1);
            saveArorder.setDtcheck(new Date());
            if("30".equals(smreceivablecodesmain.getPayeestatus())){
                //收款人确认
                saveArorder.setVcreceiveuserno(smreceivablecodesmain.getModifieduser());
                //收款时间
                saveArorder.setDtreceive(new Date(Long.parseLong(smreceivablecodesmain.getGmtmodified())));
                //收款金额
                saveArorder.setDcreceive(Double.parseDouble(detail.getSettlecost()));
            }
            /*生成应收对账单*/
            saveArorder.setIaccount(1);
            saveArorder.setVcaccountuserno(smreceivablecodesmain.getModifieduser());
            saveArorder.setVcaccountno(smreceivablecodesmain.getBillcode());
            saveArorder.setDtaccount(new Date());
            /*确定对账*/
            saveArorder.setIbill(1);
            saveArorder.setDtbill(new Date());
            saveArorder.setVcbilluserno(smreceivablecodesmain.getModifieduser());


            //查询判断是否已经存在，存在更新，不存在插入
            List<ArorderSo>  existArorder=arorderMapper.selectByIshiplineid(ar.getIshiplineid());

            if (existArorder.size()>0)  {
               arorderMapper.updateByIshiplineid(saveArorder);
            }else  {
               arorderMapper.insertArorder(saveArorder);
            }
            //更新明細狀態為1
            smreceivablecodesdetailMapper.updateByIlineid(detail.getIlineid());
            iflag ++;
        }
        if(list.size() == iflag){
            return true;
        }
        return false;
    }

        //获取慧运车最新被修改的应收账单号列表。
        @Override
        public void getCodes() throws Exception {
            String data = callHYCUrlReceiveService.callHYCUrlReceive(RECCODES, null);
            //将接口返回的数据进行拆分；
            List<ReceivableCodesDB> receivableCodesDB= JSONObject.parseArray(data,ReceivableCodesDB.class);
            if(CollectionUtils.isNotEmpty(receivableCodesDB)){
                for(int i = 0; i < receivableCodesDB.size() ; i++ ){
                    ReceivableCodesDB receivableCode = receivableCodesDB.get(i);
                    LOGGER.debug("得到应收账单号列表"+receivableCode.getCode());
                    ReceivableDetail(receivableCode.getCode());
                }
            }

        }
        /**
         *获取提交应付账单明細
         * @param
         */
        public void ReceivableDetail(String code) throws Exception{
            //根据订单号获取订单详细信息
            String data = callHYCUrlReceiveService.callHYCUrlReceive(RECDETAIL,code);
            ReceivableBillMain db = JSONObject.parseObject(data, ReceivableBillMain.class);
            saveReceivableBillMain(db);
        }

        /**
         * 保存数据主表中
         * @param db  数据
         */
        public void saveReceivableBillMain(ReceivableBillMain db){
            Smreceivablecodesmain smreceivablecodesmain = new Smreceivablecodesmain();
            BeanUtils.copyProperties(db,smreceivablecodesmain);
            //转换Comment
            if (null!=db.getComment()){
                smreceivablecodesmain.setComments(db.getComment());
            }
            smreceivablecodesmainMapper.insertRecMain(smreceivablecodesmain);
            saveReceivableBillDetail(db.getBillDetailList());
        }

        /**
         * 保存数据明細中
         * @param db  数据
         */
        public void saveReceivableBillDetail(List<ReceivableBillDetail> db){
            for(int i = 0; i < db.size() ; i++ ){
                Smreceivablecodesdetail  smreceivablecodesdetail = new Smreceivablecodesdetail();
                ReceivableBillDetail receivableBillDetail = db.get(i);
                BeanUtils.copyProperties(receivableBillDetail,smreceivablecodesdetail);
                //转换Comment
                if (null!=receivableBillDetail.getComment()){
                    smreceivablecodesdetail.setComments(receivableBillDetail.getComment());
                }
                LOGGER.debug("得到車vehicleName"+smreceivablecodesdetail.getVehiclename());
                smreceivablecodesdetail.setVcflag("0");
                smreceivablecodesdetailMapper.insertRecDetail(smreceivablecodesdetail);
            }
        }

    /**
     * 现金收款标记
     * @throws Exception
     */
    @Override
    public void cashReceipts() throws Exception {
        //1、查询所有的慧运车现金订单
        List<Hycorder> list = hycorderMapper.getOrderByReceipts();
        if(CollectionUtils.isNotEmpty(list)){
            for (Hycorder hycorder : list) {
                Long firstLineId = 0L;
                //2、检查这些订单是否已经生成运单
                Soorder  soorder =  soorderMapper.getOrderByOrderNo(hycorder.getOrdercode());
                try {
                    //2.5 判断该订单是中联承运还是惠运车承运！
                    if(soorder.getIsdispatch() == 0) {//惠运车承运的订单
                        //3、已有发运的情况下找到第一条调度指令，并将订单的现金金额写到第一条调度指令中去，并将该订单标记为已做收款标记
                        Long FirstId = this.getFirstOrderId(soorder);
                        SoshiplineExample example = new SoshiplineExample();
                        example.createCriteria().andIorderid2EqualTo(FirstId);
                        List<Soshipline> shipLineList = soshiplineMapper.selectByExample(example);
                        if (CollectionUtils.isNotEmpty(shipLineList)) {
                            Soshipline soshipline = shipLineList.get(0);
                            soshipline.setDcpay(soorder.getDcpay());
                            soshipline.setDtreceipts(new Date());
                            soshiplineMapper.updatePay(soshipline);
                            //4、将该订单做标记
                            hycorder.setIsreceipts(1);
                            hycorder.setDtreceipts(new Date());
                            hycorderMapper.updateReceipts(hycorder);
                        } else {
                            LOGGER.info("未找到第一次调度对应的运单:" + soorder.getVcorderno());
                        }
                    }
                }catch (NullPointerException e) {
                    //检查异常是否已经存在
                    execptionDisposeService.saveExecption(e.toString(),soorder.getVcorderno(),CallHYCUrlTypeEnum.HYC_PAYMENTAMOUNT.getValue());
                    LOGGER.error("现金收款标记获取订单异常:"+hycorder.getOrdercode()+"异常信息："+e.toString());
                }
            }
        }
    }

    private Long getFirstOrderId(Soorder soorder){
        //1)查询该订单下的所有子订单
        List<Soorder> orderList = soorderMapper.getorderListByOrderid(soorder.getIlineid());
        //2)找出第一条子订单
        Long lineid = 0L;
        if(CollectionUtils.isNotEmpty(orderList)){
            for (int i = 0 ; i < orderList.size(); i++) {
                Soorder soorder1 = orderList.get(i);
                if(soorder1.getVcstartcity().equals(soorder.getVcstartcity())){
                    if(soorder1.getVcstartcity().equals(soorder1.getVccityname())){
                        //起运地同城配送
                        return soorder1.getIlineid();
                    }
                    if (lineid < soorder1.getIlineid()){
                        lineid = soorder1.getIlineid();
                    }
                }
            }
            return lineid;
        }
        return soorder.getIlineid();
    }

//    private Long getFirstOrderId(Soorder soorder){
//        //1)查询该订单下的所有子订单
//        List<Soorder> orderList = soorderMapper.getorderListByOrderid(soorder.getIlineid());
//        //2)找出第一条子订单
//        for (Soorder soorder1 : orderList) {
//            //获取到订单前缀
//            String[] orderno = soorder1.getVcorderno().split("SO",0);
//
//        }
//
//        return null;
//    }
}


